package org.bbelovic.devel.exercises;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;

import org.apache.commons.lang.Validate;

public class SecondKata {

    private final String pathToFile;
    private final LineProcessor processor;
    private final LineEvaluator evaluator;

    public SecondKata(final String pathToFile, final LineProcessor processor, final LineEvaluator evaluator) {
        Validate.notNull(pathToFile);
        Validate.notNull(processor);
        Validate.notNull(evaluator);
        this.pathToFile = pathToFile;
        this.processor = processor;
        this.evaluator = evaluator;
    }

    public String execute() {
        LineEvaluatorOutput output = new LineEvaluatorOutput(Integer.MAX_VALUE, "N/A");
        try (FileReader fr = new FileReader(pathToFile);
             BufferedReader br = new BufferedReader(fr)) {
            String line = null;
            while ((line = br.readLine()) != null) {
                final List<String> tokens = processor.processLine(line);
                final LineEvaluatorInput input = new LineEvaluatorInput(tokens, output.getCurrentLine(), output.getReferenceValue());
                output = evaluator.evaluate(input);
            }
            
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return output.getCurrentLine();
    }

    public String getPathToFile() {
        return this.pathToFile;
    }

    public LineProcessor getLineProcessor() {
        return this.processor;
    }

    public LineEvaluator getLineEvaluator() {
        return this.evaluator;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("SecondKata[")
          .append("pathToFile="+ getPathToFile())
          .append(", processor="+ getLineProcessor())
          .append(", evaluator="+ getLineEvaluator())
          .append("]");
        return sb.toString();
    }

}
